import Vue from 'vue'
import VueRouter from 'vue-router'

//获取路由信息
var route = require('../store/content')

Vue.use(VueRouter)


//路由基础
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  }
]

//创建路由
const router = new VueRouter({
  routes
})

//后台路由基础
var addroute = {
  path: '/',
  name: 'Home',
  component: () => import('@/views/Home.vue'),
  redirect: '/index',
  children: [{
    path: '/index',
    name: 'index',
    component: () => import('@/components/layout/Index.vue'),
  }]
}

//获取动态路由添加生成
for (let i = 0; i < route.routes.length; i++) {
  route.routes[i].children.forEach(element => {
    var news = {
      path: element.path,
      name: element.name,
      component: (resolve) => require([`@/views/${element.require}`], resolve)
    }
    addroute.children.push(news)
  });
}

//console.log(addroute)
//添加动态路由
router.addRoutes([addroute])


//挂载登陆守卫
router.beforeEach((to,from,next) => {
  //白名单
  const pass = ['/login']
  const nopass = []
  //如果在白名单页面，或者不在黑名单页面直接通过
  if(pass.indexOf(to.path) != -1||to.path.indexOf(nopass)==-1) return next();
  //访问其他页面时判断token，
  const userToken = window.sessionStorage.getItem('username');
  //token存在通过
  if(userToken) return next();
  //token不存在提示且跳转登录页
  Vue.prototype.$message.error('请先登录')
  next('/login');
})



export default router
